package com.zbf.tspring.service;

import com.zbf.tspring.dao.TestDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/22  9:37
 * 描述: 测试不同的类中的 事务嵌套行为  使用 TestService3    测试   TestService4
 */

@Component
public class TestService3 {

      @Autowired
      private TestDao testDao;

      @Autowired
      private TestService4 testService4;

      @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
      public  void test31() throws ExecutionException, InterruptedException {
          Map<String,Object> map=new HashMap<>();
          map.put("id",3);
          map.put("quantity",300);
          int i = testDao.updateStock(map);

          FutureTask task=new FutureTask(new Callable() {
              @Override
              public Object call() throws Exception {
                  testService4.test41();
                  return "ok";
              }
          });
          Thread thread = new Thread(task);

          thread.start();
          //等待执行结果，当有异常的时候在这里就可以获取到异常传递给test31触发他的回滚
          Object ok = task.get();
          System.out.println("=============OK");
      }


    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public  void test41(){
        Map<String,Object> map=new HashMap<>();
        map.put("id",3);
        map.put("quantity",300);
        int i = testDao.updateStock(map);


        testService4.test41();
    }

}
